#include "Peon.h"
#include "../Player/Player.h"
#include "../../../SGD_Wrappers/CSGD_EventSystem.h"
#include "../../../SGD_Wrappers/CSGD_TextureManager.h"
#include "../../../SGD_Wrappers/CSGD_MessageSystem.h"
#include "../../../SGD_Wrappers/IMessage.h"
#include "../../DestroyEntityMessage.h"

CPeon::CPeon(void)
{
	this->m_eType = ENTITY_ENEMY;
	m_nDamage = 10;
	m_fAttackRate = 0.0f;
	this->SetPosX(100);
	SetPosY(100);
	SetVelX(0);
	SetVelY(0);
	this->m_eType = ENTITY_ENEMY;
	this->SetHealth( 20 );

	CSGD_EventSystem::GetInstance()->RegisterClient("PEON_ATTACK",this);

}
void CPeon::Init()
{
	m_nDamage = 10;
	m_fAttackRate = 0.0f;
	this->SetPosX(100);
	SetPosY(100);
	SetVelX(0);
	SetVelY(0);
	this->m_eType = ENTITY_ENEMY;
	this->SetHealth( 20 );
}

CPeon::CPeon(CPlayer* pTarget)
{
	m_pTarget = pTarget;
	m_pTarget->AddRef();
}

CPeon::~CPeon(void)
{
	m_pTarget->Release();
}

void CPeon::Render()
{
	CSGD_TextureManager* pTM = CSGD_TextureManager::GetInstance();
	pTM->Draw(pTM->LoadTexture(_T("resource/graphics/FNV_zombie.png")),(int)this->GetPosX(),(int)this->GetPosY(),1.0f,1.0f,
		nullptr,GetWidth()*0.5f,GetHeight()*0.5f,this->GetRotation());
}
void CPeon::Update(float fElapsedTime)
{
	m_vToTarget.fX = m_pTarget->GetPosX()+(m_pTarget->GetWidth()/2-GetPosX());
	m_vToTarget.fY = m_pTarget->GetPosY()+(m_pTarget->GetHeight()/2-GetPosY());

	tVector2D vOrientation = {0,-1};
	vOrientation = Vector2DRotate(vOrientation,this->GetRotation());
	float fAngle = AngleBetweenVectors(vOrientation,m_vToTarget);
	float fMaxRot = (SGD_PI/2)*fElapsedTime;
	if(fAngle > fMaxRot)
		fAngle = fMaxRot;

	if(Steering(vOrientation, m_vToTarget)<0)
	{
		fAngle= -fAngle;
	}
	
	this->SetRotation(this->GetRotation()-fAngle);


	tVector2D vVel = {0,1};
	vVel = vVel * (float)this->GetMoveSpeed();
	vVel = Vector2DRotate(vVel,this->GetRotation());
	this->SetVelX(vVel.fX);
	this->SetVelY(vVel.fY);

	this->SetPosX(this->GetPosX()+fElapsedTime*GetVelX());
	this->SetPosY(this->GetPosY()+fElapsedTime*GetVelY());

	m_fAttackRate-= fElapsedTime;

	if(this->CheckCollision(m_pTarget) && m_fAttackRate <= 0.0f)
	{
		CSGD_EventSystem* pES = CSGD_EventSystem::GetInstance();
		pES->SendEvent("PLAYER_ATTACK",(void*)m_nDamage,m_pTarget,this);
		m_fAttackRate = 1.0f;
	}

	if( this->GetHealth() <= 0 )
	{
		IMessage* i = new CDestroyEntityMessage( this );
		CSGD_MessageSystem::GetInstance()->SendMsg( i );
		i = nullptr;
		CSGD_EventSystem::GetInstance()->SendEvent("SCORE_INCREASE",nullptr,nullptr,this);
	}



}
RECT CPeon::GetRect()
{
	return CEntity::GetRect();
}

void CPeon::SetTarget(CPlayer* pTarget)
{
	m_pTarget = pTarget;
	pTarget->AddRef();
}


void CPeon::HandleEvent(CEvent* pEvent)
{
	if(pEvent->GetEventID() == "PEON_ATTACK")
	{
		if(this == pEvent->GetDestination())
		{
			this->TakeDamage((int)pEvent->GetParam());

		}
	}
}
